package com.csi.jf.crucible.ptservice.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinasofti.ro.bizframework.core.data.validation.Validation;
import com.chinasofti.ro.bizframework.core.mvc.Controller;
import com.chinasofti.ro.bizframework.core.mvc.View;
import com.chinasofti.ro.bizframework.core.orm.Page;
import com.chinasofti.ro.bizframework.core.orm.PageUtil;
import com.chinasofti.ro.bizframework.core.orm.entity.Model;
import com.chinasofti.ro.bizframework.modules.json.JSONArray;
import com.csi.jf.crucible.common.config.JfConstants;
import com.csi.jf.crucible.common.util.LoginUtils;
import com.csi.jf.crucible.ptservice.model.CodePackages;
import com.csi.jf.crucible.ptservice.model.PrjAssociate;
import com.csi.jf.crucible.ptservice.model.SonarDaily;
import com.csi.jf.crucible.ptservice.model.Sonarservices;
import com.csi.jf.crucible.ptservice.model.ToolServices;
import com.csi.jf.crucible.ptservice.model.ToolservicesStatus;
import com.csi.jf.crucible.ptservice.model.ToolservicesStatusPk;
import com.csi.jf.crucible.ptservice.model.ToolservicesUse;
import com.csi.jf.crucible.ptservice.service.SonarservicesService;

/**
 * <p>Controller</p>
 * 
 * @author BizFoundation
 * @version 1.0
 * @since 1.0
 */
public class SonarservicesController extends Controller {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * <p>打开查询列表页面</p>
	 * 
	 */
	public void list() {
		View view = new View(SUCCESS);
		this.render(view);
	}
	/**
	 * <p>开通服务</p>
	 * 
	 */
	public void openToolService(Long serviceId) {
	    //
	    ToolservicesStatus  tss = new ToolservicesStatus();
        tss.setStatus(JfConstants.PTS_TOOL_UNUSE);
        ToolservicesStatusPk toolservicesStatusPk = new ToolservicesStatusPk();
        Long projectId = LoginUtils.getCurrentProject().getProjectId();
        toolservicesStatusPk.setProjectId(projectId);
	    toolservicesStatusPk.setServiceId(serviceId);
        tss.setToolservicesStatusPk(toolservicesStatusPk );
//		Sonarservices sonarservices = new Sonarservices();
//		sonarservices.setCreateTime(new Timestamp(System.currentTimeMillis()));
//	    sonarservices.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//		sonarservices.setCreator(LoginController.getLoginUser().getJfid());
//		sonarservices.setProjectId(Long.valueOf(LoginController.getCurrentProject().getProjectid()));
//		if(serviceId !=null){
//		    sonarservices.setServiceId(serviceId);
//		    sonarservices.setServiceName(sonarservicesService.findToolSerByID(serviceId).getToolname());
//		}
//		sonarservices.setStatus(JfConstants.PTS_TOOL_UNUSE);//开通未使用
		sonarservicesService.save(tss);
	    View view = new View(SUCCESS);
	    view.bind("serviceId", serviceId);
        this.render(view);
	}
	/**
	 * <p>返回申请使用的服务状态</p>
	 * 
	 */
	public void showApply(Long serviceId) {
		Map<String,Object> statusMap = new HashMap<String,Object>();
//		//默认为未开通状态
		Integer status = JfConstants.PTS_TOOL_UNOPEN;
		HttpSession session = request().getSession(false);
		Long projectId = LoginUtils.getCurrentProject().getProjectId();
		ToolservicesStatus tss = sonarservicesService.findToolServiceStatus(projectId, serviceId);
		if(tss != null){
		    //服务已开通
			status = JfConstants.PTS_TOOL_UNUSE;
			statusMap.put("serviceId", serviceId);
		}
		statusMap.put("status", status);
        JSONArray json = JSONArray.fromObject(statusMap);
        this.renderJSON(json.toString());
	}
	
	public void listToolServices(){
		//查询所有PTS工具服务
		List<ToolServices> toollist = sonarservicesService.findAllToolSer();
		JSONArray json = JSONArray.fromObject(toollist);
		this.renderJSON(json.toString());
	}
	/**
	 * 显示开通工具服务页面
	 * @param serviceId
	 */
	public void showopen(Long serviceId){
	    View view = new View(SUCCESS);
	    view.bind("serviceId", serviceId);
        this.render(view);
	}
	/**
	 * 显示使用工具服务页面（服务已开通）
	 * @param serviceId
	 */
	public void showRun(Long serviceId){
	    View view = new View(SUCCESS);
	    view.bind("serviceId", serviceId);
        this.render(view);
	}
	
	/**
	 * 显示工具服务使用详情页面（服务已使用）
	 * @param serviceId
	 */
	public void showStatus(Long serviceHistoryId){
        View view = new View(SUCCESS);
        ToolservicesUse tsu = (ToolservicesUse) this.sonarservicesService
                .findToolServiceHistoryById(serviceHistoryId);
        //根据服务使用历史找出服务ID和包ID
        view.bind("serviceId", tsu.getServiceId());
        view.bind("codePackageId", tsu.getProjectId());
        this.render(view);
    }
	
	/**
	 * 使用工具服务
	 * @param ServiceID
	 * @param codePackageId
	 * @throws Exception
	 */
	public void useToolService(Long serviceId,Long codePackageId)throws Exception{
		Long projectId = LoginUtils.getCurrentProject().getProjectId();
		//生成一条使用记录
		ToolservicesUse tsu = new ToolservicesUse();
        if(serviceId!=null){
            tsu.setServiceId(serviceId);
            tsu.setServiceName((sonarservicesService.findToolServiceById(serviceId)).getToolname());
        }
        tsu.setProjectId(Long.valueOf(projectId));
        tsu.setCodePackageId(codePackageId);
        tsu.setStatus(JfConstants.PTS_TOOL_USEING);
        tsu.setCreateTime(new Timestamp(System.currentTimeMillis()));
        tsu.setCreator(LoginUtils.getLoginUser().getJfid());
        tsu.setUpdater(0L);
        tsu.setUpdateTime(tsu.getCreateTime());
        sonarservicesService.save(tsu); 
        
        //执行工具服务
        if (codePackageId != null) {
            analyze(Long.valueOf(codePackageId), projectId,serviceId);
        }
        
	    View view = new View(SUCCESS);
	    view.bind("serviceId", serviceId);
	    view.bind("codePackageId", codePackageId);
        this.render(view);
	}
	
	/**
	 * 显示单个工具服务信息
	 * @param serviceId
	 */
    public void getServiceInfo(Long serviceId) {
        ToolServices ts = (ToolServices) this.sonarservicesService
                .findToolServiceById(serviceId);
        this.renderJSON(ts);
    }
	/**
	 * 显示当前服务使用的代码包信息
	 * @param codePackageId
	 */
    public void getServicePackageInfo(Long codePackageId) {
        CodePackages cp = (CodePackages) this.sonarservicesService
                .findCodePacakgeById(codePackageId);
        this.renderJSON(cp);
    }
    
	/**
	 * 显示使用服务的日志
	 * @param codePackageId
	 */
    public void showDaily(Long serviceId,Long projectId) {
    	ToolservicesUse tsu = sonarservicesService.findToolservicesUse(projectId, serviceId);
    	List<SonarDaily> list = new ArrayList<SonarDaily>();
    	list = sonarservicesService.findAllSonarDaily(tsu.getId());
    	JSONArray json = JSONArray.fromObject(list);
        this.renderJSON(json.toString());
    }
	
	/**
	 * <p>查询分页数据</p>
	 * @param gridPage
	 * @param sonarservices
	 */
	public void listSonarservices(Page page,ToolservicesUse toolservicesUse) {
		page = sonarservicesService.findByPage(toolservicesUse, page);
		this.renderJSON(PageUtil.toJson4JqGrid(page, true));
	}

	public void show(Long id) {
		if(null == id){
			throw new NullPointerException("主键为Null");
		}
		Model sonarservices = sonarservicesService.findCodePacakgeById(id);
		View view = new View(SUCCESS);
		view.bind("sonarservices",sonarservices);
		this.render(view);
	}
	
	public void add() {
		this.render(SUCCESS);
	}

	public void save(Sonarservices sonarservices) {
		if (Validation.hasErrors()) {
			View view = new View(FAILED);
			view.bind("sonarservices",sonarservices);
			this.render(view);
			return;
		}
		//TODO 把创建人和更新人改在当前登录人
		sonarservices.setCreator(0L);
		sonarservices.setCreateTime(new Timestamp(System.currentTimeMillis()));
		sonarservices.setUpdater(0L);
		sonarservices.setUpdateTime(sonarservices.getCreateTime());
		sonarservicesService.save(sonarservices);
		View view = new View(SUCCESS);
		this.success("add.success");
		redirect(view);
	}

	public void edit(Long id) {
		if(null == id){
			throw new NullPointerException("主键为Null");
		}
		Model sonarservices = sonarservicesService.findCodePacakgeById(id);
		View view = new View(SUCCESS);
		view.bind("sonarservices",sonarservices);
		this.render(view);
	}

	public void update(Sonarservices sonarservices) {
	    sonarservices.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		sonarservicesService.update(sonarservices);
		View view = new View(SUCCESS);
		this.success("update.success");
		this.redirect(view);
	}

	public void delete(String ids) {
		this.sonarservicesService.batchDelete(ids);
		View view = new View(SUCCESS);
		this.success("delete.success");
		this.redirect(view);
	}
	
	/**
	 * 执行一次代码质量分析服务
	 * @param codePackageId
	 * @throws Exceptio
	 */
	public void analyze(Long codePackageId,Long prjID,Long serviceId) throws Exception{
	    try {
            CodePackages cp = (CodePackages)this.sonarservicesService.findCodePacakgeById(codePackageId);
			PrjAssociate prjAssociate = new PrjAssociate();
			prjAssociate = sonarservicesService.findByPrjID(prjID);
			//记录日志
			ToolservicesUse tsu = (ToolservicesUse)sonarservicesService.findToolservicesUse(prjID, serviceId);
			SonarDaily sonarDaily = new SonarDaily();
			sonarDaily.setServiceusedid(tsu.getId());
            if(cp!=null){
                this.sonarservicesService.createWorkspace(cp.getProjectId(),sonarDaily);
                this.sonarservicesService.retreiveCodeFromPackage(codePackageId,sonarDaily);
                this.sonarservicesService.createSonarProjectCfg(cp,prjAssociate,sonarDaily);
                this.sonarservicesService.runSonarRunner(codePackageId,sonarDaily);
                this.sonarservicesService.clearWorkspace(cp.getProjectId(),sonarDaily);
                this.sonarservicesService.setProjectPermission(prjAssociate);
                //this.sonarservicesService.showSonarDashboardUrl(prjAssociate);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
/*            View view = new View(FAILED);
            this.success("analyze.failed");
            this.redirect(view);*/
            return;
        }
/*        View view = new View(SUCCESS);
        this.success("analyze.success");
        this.redirect(view);*/
	}

    /**
     * <p>注入 sonarservicesService</p>
     */
    private SonarservicesService sonarservicesService;

	public void setSonarservicesService(SonarservicesService sonarservicesService) {
		this.sonarservicesService = sonarservicesService;
	}
}